<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="Content/Layui-KnifeZ/css/layui.css" rel="stylesheet" />
		<script src="Content/Layui-KnifeZ/layui.js"></script>
		<script src="Content/ace/ace.js"></script>
	</head>
	<body onload="NewOne()">
		<div>
			<fieldset class="layui-elem-field layui-field-title">
				<legend>文章标题</legend>
			</fieldset>

			<input type="text" name="title" required lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">

			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
				<legend>文章分类</legend>
			</fieldset>
			<form class="layui-form" action="">
				<input type="radio" name="category" value="栏目A" title="栏目A" checked>
				<input type="radio" name="category" value="栏目B" title="栏目B" checked>
				<input type="radio" name="category" value="栏目C" title="栏目C" checked>
			</form>
			
			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
				<legend>文章简介</legend>
			</fieldset>
			<textarea name="news_text" required lay-verify="required" placeholder="请输入" class="layui-textarea"></textarea>

			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
				<legend>文章标题图片</legend>
			</fieldset>

			<div class="layui-upload">
				<button type="button" class="layui-btn" id="test1">上传标题图片</button>
				<div class="layui-upload-list" style="width: auto; height: auto; border: 5px solid #C2BE9E;">
					<img class="layui-upload-img" id="demo1">
					<p id="demoText"></p>
				</div>
			</div>

			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
				<legend>发布时间</legend>
			</fieldset>
			<div class="layui-inline">
				<!-- 注意：这一层元素并不是必须的 -->
				<input type="text" class="layui-input" id="time_demo1">
			</div>

			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
				<legend>文章内容</legend>
			</fieldset>
			<div class="layui-form">
				<div class="layui-form-item">
					<textarea id="layeditDemo"></textarea>
				</div>
			</div>
			
			<button type="button" class="layui-btn layui-btn-fluid" style="margin: 10px;" onclick="buttonOn()">提交修改</button>
		</div>		
		<script>
			var nameid = 123456;
			var windows_layer;
			var windows_layedit,windows_ieditor;
			var index_loding;
			var titleUrl;
				layui.use(['upload', 'layer', 'layedit', 'jquery', 'laydate'], function() {
					var $ = layui.jquery;
					var layedit = layui.layedit;
					var upload = layui.upload;
					var layer = layui.layer;
					var laydate = layui.laydate;
					
					windows_layer=layer;
					console.log("windows_layer加载完成");
					
					
					//执行实例，上传图片标题
					var uploadInst = upload.render({
						elem: '#test1' //绑定元素
							,
						url: '/index.php/news/do_upload_image', //上传接口
						size: 2048 //上传文件大小
							,
						exts: 'gif|jpg|png' //上传文件后缀
							,
						done: function(res) {
							//上传完毕回调
							console.log(res);
							//如果上传失败
							if (res.code > 0) {
				
								return layer.msg('上传失败,注意文件格式以及宽高度。');
							}
							//上传成功
							document.getElementById("demo1").src = res.data.src;
							return layer.msg('上传成功。');
						},
						error: function() {
							//请求异常回调
						}
					});
					//时间控制器
					//执行一个laydate实例
					laydate.render({
						elem: '#time_demo1' //指定元素
					});
				
					layedit.set({
						//暴露layupload参数设置接口 --详细查看layupload参数说明
						uploadImage: {
							url: 'your url',
							accept: 'image',
							acceptMime: 'image/*',
							exts: 'jpg|png|gif|bmp|jpeg',
							size: 1024 * 10,
							data: {
								name: "测试参数",
								age: 99
							},
							done: function(data) {
								console.log(data);
							}
						},
						uploadVideo: {
							url: 'your url',
							accept: 'video',
							acceptMime: 'video/*',
							exts: 'mp4|flv|avi|rm|rmvb',
							size: 1024 * 10 * 2,
							done: function(data) {
								console.log(data);
							}
						},
						uploadFiles: {
							url: 'your url',
							accept: 'file',
							acceptMime: 'file/*',
							size: '20480',
							autoInsert: true, //自动插入编辑器设置
							done: function(data) {
								console.log(data);
							}
						}
						//右键删除图片/视频时的回调参数，post到后台删除服务器文件等操作，
						//传递参数：
						//图片： imgpath --图片路径
						//视频： filepath --视频路径 imgpath --封面路径
						//附件： filepath --附件路径
						,
						calldel: {
							url: 'your url',
							done: function(data) {
								console.log(data);
							}
						},
						rightBtn: {
							type: "layBtn", //default|layBtn|custom  浏览器默认/layedit右键面板/自定义菜单 default和layBtn无需配置customEvent
							customEvent: function(targetName, event) {
								//根据tagName分类型设置
								switch (targetName) {
									case "img":
										alert("this is img");
										break;
									default:
										alert("hello world");
										break;
								};
								//或者直接统一设定
								//alert("all in one");
							}
						}
						//测试参数
						,
						backDelImg: true
							//开发者模式 --默认为false
							,
						devmode: true
							//是否自动同步到textarea
							,
						autoSync: true
							//内容改变监听事件
							,
						onchange: function(content) {
								console.log(content);
							}
							//插入代码设置 --hide:false 等同于不配置codeConfig
							,
						codeConfig: {
							hide: true, //是否隐藏编码语言选择框
							default: 'javascript', //hide为true时的默认语言格式
							encode: true //是否转义
								,
							class: 'layui-code' //默认样式
						}
						//新增iframe外置样式和js
						,
						quote: {
							style: ['Content/css.css'],
							//js: ['/Content/Layui-KnifeZ/lay/modules/jquery.js']
						}
						//自定义样式-暂只支持video添加
						//, customTheme: {
						//    video: {
						//        title: ['原版', 'custom_1', 'custom_2']
						//        , content: ['', 'theme1', 'theme2']
						//        , preview: ['', '/images/prive.jpg', '/images/prive2.jpg']
						//    }
						//}
						//插入自定义链接
						,
						customlink: {
							title: '插入layui官网',
							href: 'https://www.layui.com',
							onmouseup: ''
						},
						facePath: 'http://knifez.gitee.io/kz.layedit/Content/Layui-KnifeZ/',
						devmode: true,
						videoAttr: ' preload="none" '
							//预览样式设置，等同layer的offset和area规则，暂时只支持offset ,area两个参数
							//默认为 offset:['r'],area:['50%','100%']
							//, previewAttr: {
							//    offset: 'r'
							//    ,area:['50%','100%']
							//}
							,
						tool: [
							'html', 'undo', 'redo', 'code', 'strong', 'italic', 'underline', 'del', 'addhr', '|', 'removeformat',
							'fontFomatt', 'fontfamily', 'fontSize', 'fontBackColor', 'colorpicker', 'face', '|', 'left', 'center',
							'right', '|', 'link', 'unlink', 'images', 'image_alt', 'video', 'attachment', 'anchors', '|', 'table',
							'customlink', 'fullScreen', 'preview'
						],
						height: '500px'
					});
					var ieditor = layedit.build('layeditDemo');
					windows_ieditor=ieditor;
					// layedit.setContent(ieditor, "hello wyc", false);
					windows_layedit=layedit;
				});
		</script>

		<script>		
			UrlParam = function() { // url参数
				var data, index;
				(function init() {
					data = []; //值，如[["1","2"],["zhangsan"],["lisi"]]
					index = {}; //键:索引，如{a:0,b:1,c:2}
					var u = window.location.search.substr(1);
					if (u != '') {
						var params = decodeURIComponent(u).split('&');
						for (var i = 0, len = params.length; i < len; i++) {
							if (params[i] != '') {
								var p = params[i].split("=");
								if (p.length == 1 || (p.length == 2 && p[1] == '')) { // p | p= | =
									data.push(['']);
									index[p[0]] = data.length - 1;
								} else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c 舍弃
									continue;
								} else if (typeof(index[p[0]]) == 'undefined') { // c=aaa
									data.push([p[1]]);
									index[p[0]] = data.length - 1;
								} else { // c=aaa
									data[index[p[0]]].push(p[1]);
								}
							}
						}
					}
				})();
				return {
					// 获得参数,类似request.getParameter()
					param: function(o) { // o: 参数名或者参数次序
						try {
							return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);
						} catch (e) {}
					},
					//获得参数组, 类似request.getParameterValues()
					paramValues: function(o) { // o: 参数名或者参数次序
						try {
							return (typeof(o) == 'number' ? data[o] : data[index[o]]);
						} catch (e) {}
					},
					//是否含有paramName参数
					hasParam: function(paramName) {
						return typeof(paramName) == 'string' ? typeof(index[paramName]) != 'undefined' : false;
					},
					// 获得参数Map ,类似request.getParameterMap()
					paramMap: function() {
						var map = {};
						try {
							for (var p in index) {
								map[p] = data[index[p]];
							}
						} catch (e) {}
						return map;
					}
				}
			}();
			
			
			// get方法 传入url，返回data
			function loadXMLDoc_get(url)
			{
				// setTimeout(function (){
					//index_loding=windows_layer.load(0);  //加载loding
				// }, 2000);
				var read=document.getElementsByName("category");
				read[0].checked=true;
				console.log("url=" + url);
				var xmlhttp;
				if (window.XMLHttpRequest) {
					// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
					xmlhttp = new XMLHttpRequest();
				} else {
					// IE6, IE5 浏览器执行代码
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				xmlhttp.onreadystatechange = function() {
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
						var data = xmlhttp.responseText;
						console.log(data);
						console.log(JSON.parse(data));
						json_data = JSON.parse(data);
			
						//写入标题
						document.getElementsByName("title")[0].value = json_data.data[0].title;
						console.log("category="+json_data.data[0].category);
						if (json_data.data[0].category == null || json_data.data[0].category == "") {
							//默认就选第一个
							document.getElementsByName("category")[0].checked = "checked";
							console.log("category0")
						} else if (json_data.data[0].category == "栏目A") {
							document.getElementsByName("category")[0].checked = "checked";
							console.log("category0")
						} else if (json_data.data[0].category == "栏目B") {
							document.getElementsByName("category")[1].checked = "checked";
							console.log("category1")
						} else if (json_data.data[0].category == "栏目C") {
							document.getElementsByName("category")[2].checked = "checked";
							console.log("category2")
						}else{
							console.log("写入失败，无法判断");
							console.log("category,x")
						}
						//写入标题图片
						document.getElementById("demo1").src = json_data.data[0].title_url;
						titleUrl=json_data.data[0].title_url;
						//写入文章简介
						document.getElementsByName("news_text")[0].value = json_data.data[0].introduction;
			
						//写入时间
						document.getElementById("time_demo1").value = json_data.data[0].time;
						
						//富文本内容赋值
						var kz_layedit =document.getElementById("layeditDemo");
						
						kz_layedit.innerHTML=json_data.data[0].content;
						
						
						//windows_layer.close(index_loding); //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算的
						console.log("加载完成");
					
					}
					}
				xmlhttp.open("GET", url, false);
				xmlhttp.send();
			}
			
			//监听提交修改按钮
			function buttonOn () {
				console.log("点击提交按钮");
				//询问框
				windows_layer.confirm('确定要提交修改文章？', {
				  btn: ['确定','取消'] //按钮
				}, function(){
				  windows_layer.msg('正在修改中。', {icon: 1});
				  // console.log("windows_layer加载完成");
				  index_loding=layer.load(0);  //加载loding
				  //提交修改
				  http_modify();
				}, function(){
				  windows_layer.msg('点击了取消。', {icon: 1});
				});
			}
			//提交修改
			function http_modify() {
				  var xmlhttp;
				  if (window.XMLHttpRequest)
				  {
				    // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
				    xmlhttp=new XMLHttpRequest();
				  }
				  else
				  {
				    // IE6, IE5 浏览器执行代码
				    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
				  }
				  xmlhttp.onreadystatechange=function()
				  {
				    if (xmlhttp.readyState==4 && xmlhttp.status==200)
				    {
					  console.log(xmlhttp.responseText);
					  windows_layer.close(index_loding);
					  var index = parent.layer.getFrameIndex(window.name);
					  parent.layer.close(index);
				    }
				  }
				  xmlhttp.open("POST","/index.php/news/modify_news",true);
				  xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
				  //获取数据
				  //id
				  var news_id=UrlParam.paramValues("id")[0];
				  //title
				  var news_title=document.getElementsByName("title")[0].value;
				  //title_url
				  var news_title_url=titleUrl;
				  //Introduction
				  var news_introduction=document.getElementsByName("news_text")[0].value;
				  //time
				  var news_time=document.getElementById("time_demo1").value;
				  //content
				  var news_content=windows_layedit.getContent(windows_ieditor);
				  //category
				  var news_category=getRadioValue("category");
				  console.log("news_id=",news_id);
				  console.log("news_title=",news_title);
				  console.log("news_title_url=",news_title_url);
				  console.log("news_introduction=",news_introduction);
				  console.log("news_time=",news_time);
				  console.log("news_content=",news_content);
				  console.log("news_category=",news_category);
				  //拼接到一起
				  news_content=encodeURIComponent(news_content);
				  var str="id="+news_id+
				  "&title="+news_title+
				  "&title_url="+news_title_url+
				  "&introduction="+news_introduction+
				  "&time="+news_time+
				  "&content="+news_content+
				  "&category="+news_category;
				  console.log("str，="+str);
				  xmlhttp.send(str);
			}
			
			function getRadioValue(radioName) {
				var radios = document.getElementsByName(radioName);
				var value;
				for (var i = 0; i < radios.length; i++) {
					if (radios[i].checked) {
						value = radios[i].value;
						break;
					}
				}
				return value;
			}
			
			
			function NewOne() {
				// index_loding=windows_layer.load(0);  //加载loding
				var news_id = UrlParam.paramValues("id")[0];
				console.log(news_id);
				//根据传过来的id，访问所有id文章数据，并且返回
				loadXMLDoc_get("/index.php/news/id_news?id=" + news_id);
			}
		</script>
	</body>
</html>
